# -*- coding: utf-8-*-
from openerp.osv import osv
import json


class res_users(osv.osv):
    _inherit = 'res.users'

    def check_vals(self, cr, uid, vals, context=None):
        # 调用res.partner的验证程序
        self.pool.get('res.partner').check_vals(cr, uid, vals, context=context)

    def gather_vals(self, cr, uid, ids, context=None):
        # 获取所有用户的partner_id的集合，交给res.partner来处理获取数据
        partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context=context)]

        return self.pool.get('res.partner').gather_vals(cr, uid, partner_ids, context=context)

    def sync_values(self, cr, uid, vals, context=None):
        # 将数据交由res.partner来处理
        self.pool.get('res.partner').sync_values(cr, uid, vals, context=context)


class res_partner(osv.osv):
    _inherit = 'res.partner'

    DEPARMENT_XMLID = {
        'user': 'dftg_weixin.weixin_department_user',
        'customer': 'dftg_weixin.weixin_department_customer',
        'supplier': 'dftg_weixin.weixin_department_supplier',
    }

    def check_vals(self, cr, uid, vals, context=None):
        # 不需要验证
        return vals

    def _get_department_id_by_name(self, cr, uid, name, partner):
        # 动态的获取user、supplier、customer的department_id
        department_obj = self.pool.get('wechat.department')
        employee_obj = self.pool.get('hr.employee')
        user_row = partner.user_id
        employee_ids = employee_obj.search(cr, uid, [('user_id', '=', user_row.id)], context=None)
        wechat_department_id = False
        if employee_ids:
            employee_rows = employee_obj.browse(cr, uid, employee_ids, context=None)
            if employee_rows[0].department_id:
                wechat_department_id = department_obj.search(cr, uid, [('system_department_id', '=', employee_rows[0].department_id.id)])
        if wechat_department_id:
            department = department_obj.read(cr, uid, wechat_department_id[0], ['name', 'department_id'])
            if department.get('department_id'):
                return department.get('department_id')
            raise osv.except_osv(u'错误', u'部门%s中没有找到对应的部门id' % department.get('name'))
        raise osv.except_osv(u'错误', u'输入了一个无法匹配的名称，无法匹配到现有的部门')

    def _get_department_by_partner(self, cr, uid, partner):
        # 给顶一个partner，来获取对应的微信部门的ID
        if partner.customer or partner.supplier:
            res = []
            if partner.customer:
                res.append(self._get_department_id_by_name(cr, uid, 'customer', partner))

            if partner.supplier:
                res.append(self._get_department_id_by_name(cr, uid, 'supplier', partner))

            return res

        return [self._get_department_id_by_name(cr, uid, 'user', partner)]

    def _get_partner_user(self, cr, uid, partner):
        res = []
        if partner.is_weixin_contacts_changed:
            vals = []
            for contacts in (contacts for contacts in partner.contacts_ids if not contacts.contacts_id):
                vals.append(self._get_vals_by_pratner(cr, uid, partner, weixin_contacts=contacts))

            if not vals and not partner.child_contacts_ids and partner.mobile:
                vals.append(self._get_vals_by_pratner(cr, uid, partner))

            res.extend(vals)

        for contacts in partner.child_contacts_ids:
            if contacts.is_weixin_contacts_changed:
                vals = []
                for weixin_contacts in contacts.contacts_ids:
                    vals.append(self._get_vals_by_contacts(cr, uid, contacts, weixin_contacts=weixin_contacts))

                if not vals:
                    vals.append(self._get_vals_by_contacts(cr, uid, contacts))

                res.extend(vals)

        return res

    def _get_vals_by_pratner(self, cr, uid, partner, weixin_contacts=None):
        res = {}
        field_list = ['name', 'mobile', 'email', 'department']
        if weixin_contacts:
            update_list = []
            for diff_field in field_list:
                if diff_field == 'department':
                    department = self.pool.get('res.partner')._get_department_by_partner(cr, uid, partner)
                    if json.dumps(department) != weixin_contacts.department:
                        res.update({diff_field: json.dumps(department)})
                        update_list.append('department')

                elif getattr(partner, diff_field) != getattr(weixin_contacts, diff_field):
                    res.update({diff_field: getattr(partner, diff_field)})
                    update_list.append(diff_field)

            res.update({
                    'update_list': json.dumps(update_list),
                    'sync_status': weixin_contacts.sync_status or 'update',
                    'weixin_contacts_id': weixin_contacts.id,
                })
        else:
            for field in field_list:
                if field == 'department':
                    department = self.pool.get('res.partner')._get_department_by_partner(cr, uid, partner)
                    res.update({field: json.dumps(department)})
                else:
                    res.update({field: getattr(partner, field)})

            res.update({
                    'partner_id': partner.id,
                    'odoo_user_id': partner and partner.user_ids and partner.user_ids[0].id or False,
                    'sync_status': 'create',
                    'origin': 'partner',
                })

        return res

    def _get_vals_by_contacts(self, cr, uid, contacts, weixin_contacts=None):
        res = {}
        field_list = ['name', 'position', 'mobile', 'email', 'department']
        if weixin_contacts:
            update_list = []
            for diff_field in field_list:
                if diff_field == 'department':
                    department = self.pool.get('res.partner')._get_department_by_partner(cr, uid, contacts.partner_id)
                    if json.dumps(department) != weixin_contacts.department:
                        res.update({diff_field: json.dumps(department)})
                        update_list.append('department')

                elif diff_field == 'position' and contacts.position != weixin_contacts.position:
                    res.update({diff_field: contacts.position})
                    update_list.append(diff_field)

                elif diff_field != 'position' and getattr(contacts.contacts_id, diff_field) != getattr(weixin_contacts, diff_field):
                    res.update({diff_field: getattr(contacts.contacts_id, diff_field)})
                    update_list.append(diff_field)

            res.update({
                    'update_list': json.dumps(update_list),
                    'sync_status': weixin_contacts.sync_status or 'update',
                    'weixin_contacts_id': weixin_contacts.id,
                    'contacts_id': contacts.id,
                })
        else:
            for field in field_list:
                if field == 'department':
                    department = self.pool.get('res.partner')._get_department_by_partner(cr, uid, contacts.partner_id)
                    res.update({field: json.dumps(department)})
                elif field == 'position':
                    res.update({field: contacts.position})
                else:
                    res.update({field: getattr(contacts.contacts_id, field)})

            res.update({
                    'partner_id': contacts.partner_id.id,
                    'contacts_id': contacts.id,
                    'odoo_user_id': contacts.partner_id and contacts.partner_id.user_ids and contacts.partner_id.user_ids[0].id or False,
                    'sync_status': 'create',
                    'origin': 'contacts',
                })

        return res

    def _get_partner_user_old(self, cr, uid, partner):
        default_address = None
        for address in partner.multi_address_ids:
            # 找到默认联系人
            if address.default:
                default_address = address
                break

        if default_address and default_address.mobile_number:
            # 如果默认联系人存在且手机号码存在, 那么就返回需要同步的数据
            return {
                'userid': default_address.mobile_number,
                'name': default_address.contacts,
                'position': default_address.duties,
                'department': self._get_department_by_partner(cr, uid, partner),
                'mobile': default_address.mobile_number,
                'gender': default_address.sexual == u'男' and 1 or 2,
                'email': default_address.email,
            }
        elif partner.mobile:
            return {
                'user_id': partner.mobile,
                'name': partner.name,
                'mobile': partner.mobile,
                'email': partner.email,
            }

        return {}

    def gather_vals(self, cr, uid, ids, context=None):
        res = []
        for partner in self.browse(cr, uid, ids, context=context):
            val = self._get_partner_user(cr, uid, partner)
            res.extend(val) if val else None

        return res

    def sync_values(self, cr, uid, vals, context=None):
        contacts_obj = self.pool.get('weixin.contacts')
        for val in vals:
            if val.get('partner_id'):
                contacts_obj.create(cr, uid, val, context=context)
            else:
                contacts_obj.write(cr, uid, val.pop('weixin_contacts_id'), val, context=context)
